'use strict';

// const Controller = require('egg').Controller;
const Controller = require('../core/base_controller');

class AdminController extends Controller {
  async login() {
    const { ctx, ctx: { service, customBody }, app: { mysql } } = this;
    const { name, password } = customBody
    // 获取参数然后保存
    var userInfo = await mysql.select('amdin_user', { where: { name, password } })
    if (1 == userInfo.length) {
      var sign = userInfo[0]
      const token = this.app.jwt.sign({
        ...sign,
        roles: 'teacher'
      }, this.app.config.jwt.secret);
      ctx.body = {
        code: 200,
        data: { token },
        msg: "登录成功"
      };
      // console.log(sign)
      // delete sign.create_time;
      // delete sign.update_time;
      // console.log(sign)

      // await mysql.update('amdin_user', { ...sign })



    } else {
      ctx.body = {
        code: 201,
        data: null,
        msg: "账号或者密码错误"
      };

    }


  }

  async userList() {
    const { ctx, ctx: { service, customBody }, app: { mysql } } = this;
    let { pageSize = 10, page = 1 } = customBody;
    let limit = pageSize,
      offset = pageSize * (page - 1);
    var where = {
      isdel: 0,
    }
    var data = await mysql.select('amdin_user', { where, limit, offset })
    var total = await mysql.select('amdin_user', { where })
    total = total.length

    this.success({

      code: 200,
      data,
      total,
      meg: "获取成功"
    })
    // ctx.body = {
    //   code: 200,
    //   data,
    //   total,
    //   meg: "获取成功"
    // };

  }
  async getUserInfo() {
    const { ctx } = this;
    const token = ctx.request.header.authorization.replace('Bearer ', '');
    let decode = '';
    if (token) {
      try {
        // 解码token
        decode = ctx.app.jwt.verify(token, this.app.config.jwt.secret);
        ctx.body = {
          code: 200,
          data: {
            ...decode,
            user_info: decode
          },
        };
        // console.log('decode======>', decode);
      } catch (error) {
        ctx.status = 401;
        ctx.body = {
          msg: error.message,
        };
        return;
      }
    } else {
      ctx.status = 401;
      ctx.body = {
        msg: '没有token',
      };
      return;
    }
  }
  async loginOut() {
    const { ctx } = this;
    ctx.body = {
      code: 200,
      msg: '退出成功',
    };
  }




}

module.exports = AdminController;

